//
//  BaseViewController.swift
//  ParkManage
//
//  Created by cf on 2020/9/17.
//  Copyright © 2020 diligrp. All rights reserved.
//

import UIKit
import EmptyDataSet_Swift
import MJRefresh

class BaseViewController: UIViewController {

    enum EmptyDataType {
        case noData, noConnection
    }
    /// 空数据页面类型
    var emptyViewType: EmptyDataType = .noData
    /// 是否显示空白页占位图
    var isDisplayEmptyDataView: Bool = false
    /// 数据源 nil 时显示的标题，默认 " "
    var emptyDataSetTitle: String = ""
    /// 数据源 nil 时显示的描述，默认 " "
    var emptyDataSetDescription: String = "暂时没有数据~"
    /// 数据源 nil 时显示的图片
    //var emptyDataSetImage = R.image.empty_data_error()
    /// 没有网络时显示的图片
    //var noConnectionImage = R.image.connect_error()
    /// 没有网络时显示的标题
    var noConnectionTitle: String = ""
    /// 没有网络时显示的描述
    var noConnectionDescription: String = "网络错误~"
    /// 垂直方向偏移量
    //var verticalOffset: CGFloat = Configs.Dimensions.topH
    /// 遵守emptyData协议的列表
    var emptyListView: UIScrollView?

    // MARK: - LifeCycle
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        makeUI()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
    }

    // MARK: - override
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // MARK: - deinit
    deinit {
        HttpService.cancelRequest()
        print("\(type(of: self)): Deinited")
    }

    // MARK: - didReceiveMemoryWarning
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        print("\(type(of: self)): Received Memory Warning")
    }

    // MARK: - init
    func makeUI() {
        
        configUITheme()
    }
    
    func configUITheme() {
        
        view.backgroundColor = .themeBackGround()
        
        navigationItem.leftBarButtonItem = 
        UIBarButtonItem(image: R.image.left_back_icon(),
                        style: .plain,
                        target: self,
                        action: #selector(backAction))
        navigationItem.leftBarButtonItem?.tintColor = .black
    }
    
    func setEmptyDataProtocolWith(listView: UIScrollView) {
        
        listView.emptyDataSetSource = self
        listView.emptyDataSetDelegate = self
        emptyListView = listView
    }
    
    func setRefreshNormalHeaderWith(listView: UIScrollView) {
        
        let header = MJRefreshNormalHeader()
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.textColor = .lightGray
        header.setTitle("下拉刷新数据", for: .idle)
        header.setTitle("松开更新数据", for: .pulling)
        header.setTitle("正在刷新数据", for: .refreshing)
        listView.mj_header  = header
        listView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(refresh))
    }
    
    func setAutoNormalFooterWith(listView: UIScrollView) {
        
        let footer = MJRefreshAutoNormalFooter()
        footer.stateLabel?.textColor = .lightGray
        footer.setTitle("全部加载完成", for: .noMoreData)
        listView.mj_footer = footer
        listView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(loadMore))
    }
    
    @objc func backAction() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc func refresh() {}
    
    @objc func loadMore() {}

}

// MARK: - EmptyDataSetSource
extension BaseViewController: EmptyDataSetSource {

    func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {

        var description = ""
        switch emptyViewType {
        case .noConnection:
            description = noConnectionDescription
        case .noData:
            description = emptyDataSetDescription
        }
        
        let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.lightGray,
                                                         .font: UIFont.systemFont(ofSize: 15)]
        return NSAttributedString(string: description, attributes: attributes)
    }

//    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
//
//        switch emptyViewType {
//        case .noConnection:
//            return noConnectionImage
//        case .noData:
//            return emptyDataSetImage
//        }
//    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {

        let string = "重新加载"
        let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.lightGray,
                                                         .font: UIFont.systemFont(ofSize: 15)]
        return NSAttributedString(string: string, attributes: attributes)
    }

    func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
        .clear
    }

    func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return -20
    }
}

// MARK: - EmptyDataSetDelegate
extension BaseViewController: EmptyDataSetDelegate {

    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return isDisplayEmptyDataView
    }
    
    @objc func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
        isDisplayEmptyDataView = false
        emptyListView?.reloadEmptyDataSet()
        if emptyListView?.mj_header == nil {
            refresh()
        } else {
            emptyListView?.mj_header?.beginRefreshing()
        }
    }

    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
        return false
    }
}
